'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import CommonResult, ErrorIds, createValidToken, AccessToken
from sent.utils.result_printer import getPrinter

from sent.model.entities.opinion import Opinion, OpinionState
from sent.model.OpinionDBManager import OpinionDBManager

class GetUserOpinions(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def get(self, *args, **kwargs):
        
        cResult = CommonResult()
        
        accessTokenStr = self.request.GET.get('access_token', None)
        baseOpId = self.request.GET.get('base_id', None)
        userExtId = self.request.GET.get('user_id', None)
        order = self.request.GET.get('order', None)
        non_neutral_only = self.request.GET.get('non_neutral_only', 0)
        include_path = self.request.GET.get('include_path', 0)
        
        try:
            offset = int(self.request.GET.get('offset', 0))
            limit = int(self.request.GET.get('limit', 50))
            max_content_length = int(self.request.GET.get('max_content_length', 0))
            max_path_content_length = int(self.request.GET.get('max_path_content_length', 0))
        except ValueError:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = 'Bad format'
            return getPrinter().printResult(cResult)
        
        if cResult.errorId == ErrorIds.SUCCESS and baseOpId and order and accessTokenStr:
            
            dbman = OpinionDBManager(True)
            try:
                baseOp = dbman.get_opinion_by_id_str(baseOpId, loadCreator=True)
                
                if baseOp:
                    assert isinstance(baseOp, Opinion)
                    
                    accessToken, error = createValidToken(accessTokenStr)
                    
                    if accessToken:
                        assert isinstance(accessToken, AccessToken)
                        if accessToken.containsScope(str(baseOp.getBaseUUID()) + ':r') \
                            or ( accessToken.containsScope('all:r') \
                                     and baseOp.containsDefaultScope('r') ):
                            
                            if not userExtId:
                                userId = accessToken.getOwnerUUID().bytes
                            
                            user_opinions, total_count = dbman.getUserOpinions(userExtId, userId, baseOp.id, non_neutral_only, order, offset, limit)
                            if total_count < 0:
                                cResult.errorId = ErrorIds.BADREQUEST
                                cResult.result = "Wrong Parameter"
                            else:
                                dbman.fillOpinionTexts(user_opinions, max_content_length)
                                
                                cResult.result = [op.toPrimitiveDict() for op in user_opinions]
                                cResult.totalResults = total_count
                                
                                if include_path:
                                    i = 0
                                    for op in user_opinions:
                                        path_to_op = dbman.get_path_to_opinions_safe(False, op, loadCreators=True)

                                        dbman.fillOpinionTexts(path_to_op, max_path_content_length)
                                        
                                        cResult.result[i]["path"] = [pathOp.toPrimitiveDict() for pathOp in path_to_op]
                                        i += 1
                                
                                cResult.errorId = ErrorIds.SUCCESS
                        else:
                            cResult.errorId = ErrorIds.UNAUTHORIZED
                            cResult.result = "No 'r' permissions for this base opinion"
                    else:
                        cResult.errorId = ErrorIds.UNAUTHORIZED
                        cResult.result = error
                else:
                    cResult.errorId = ErrorIds.NOT_FOUND
                    cResult.result = "Opinion %s not found" % baseOpId
            finally:
                dbman.closeSession()
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult)
    
    